<?php
/**
 * @file name : modulegroup.php
 * @package   :
 * @author    : Vo Thanh Minh
 * @email     : <thanhminhld@yahoo.com - thanhminhld@gmail.com>
 * @copyright : 2011
 *
 */
if (!defined('BASEPATH')) {
    exit('No direct script access');
}

class Modulegroup extends Base_Controller
{
	/**
	 * __construct
	 * @access public
	 * @param
	 * @return
	 */
	public function __construct()
	{
		parent::__construct();
	}
	/**
	  * _remap
	  * @access public
	  * @param
	  * @return
	  */
	public function _remap( $method )
	{
		switch ($method) {

		    case 'add':
		    case 'edit':
		        $this->addEditGroupModules();
		        break;

			case 'save':
				$this->saveGroupModules();
				break;

			case 'del':
			    $this->delGroupModules();
			    break;

			default:
				$this->index();
		}
	}
	/**
	 * index
	 * @access private
	 * @param
	 * @return
	 */
	private function index()
	{
	    $controlName    = $this->input->get_post('c');
	    /**
         * Get message when save insert or edit submit
         *
         */
        $msgBoxDisp = '';
        $clsType    = '';
        $clsIcon    = '';

        $messages = $this->getErrMsg($msgBoxDisp, $clsType, $clsIcon);
        /**
         * Config for paging
         */
        $arrWhere = array();
        $this->load->library('pagination');
        $config['base_url'] = 'http://' . $_SERVER["HTTP_HOST"] . dirname($_SERVER["SCRIPT_NAME"])
                            . '/?c=' . $controlName;
        $totalRows = $this->module_group_model->getTotalRows($arrWhere);
        $config['total_rows'] = $totalRows;
        $config['per_page'] = 10;
        $config['num_links'] = 2;
        $config['page_query_string'] = TRUE;

        $config['first_link'] = 'First';
        $config['last_link'] = 'Last';
        $config['next_link'] = 'Next';
        $config['prev_link'] = 'Previous';
        $config['cur_tag_open'] = '&nbsp;<font color=#FF0000><strong>';
        $config['cur_tag_close'] = '</strong></font>';

        $this->pagination->initialize($config);
        $str_paging = $this->pagination->create_links();
        $this->msmarty->assign('paging',$str_paging);

        $offset = isset($_GET['per_page']) ? $_GET['per_page'] : 0;
        /**
         * End paging
         */
		$modulesList = $this->module_group_model->loadList($arrWhere, $config['per_page'], $offset);

        $data = array('urlControlName'  => '?c=' . $controlName,
                      'modulesList'		=> $modulesList,
        			  'messages'        => $messages,
                      'clsType'         => $clsType,
                      'clsIcon'         => $clsIcon,
                      'msgBoxDisp'      => $msgBoxDisp);

		$this->msmarty->view($controlName . '/modules_group_manage', $data);
	}
	/**
     * @function addEditGroupModules
     *
     * @author   Vo Thanh Minh <thanhminhld@yahoo.com - thanhminhld@gmail.com>
     * @access   private
     * @param
     * @return
     */
	private function addEditGroupModules()
	{
	    $controlName = $this->input->get_post('c');
	    $g_id        = $this->input->get_post('id');
        /**
         * Get message when save insert or edit submit
         *
         */
        $msgBoxDisp = '';
        $clsType    = '';
        $clsIcon    = '';

        $messages   = $this->getErrMsg($msgBoxDisp, $clsType, $clsIcon);

        $groupMode  = array();
        $arrChk     = array();
        if (is_numeric($g_id) && $g_id > 0) {
            $groupMode = $this->module_group_model->loadRecord($g_id);
            $arrChk = explode(',', $groupMode->m_id);
        }
        $arrWhere   = array('parent_id' => 0);
	    $arrModule  = $this->modules_model->loadList($arrWhere, 'all');
        foreach ($arrModule as $key => $modObj) {
            if (in_array($modObj->m_id, $arrChk)) {
                $modObj->checked = 'checked';
            }
        }
        $arrModule = array_chunk($arrModule, 4);
	    $data = array('actionForm'		=> '?c=' . $controlName . '&m=save',
	                  'groupMode'		=> $groupMode,
	    			  'arrModule'		=> $arrModule,
	                  'group_id'        => $g_id,
	    			  'messages'        => $messages,
                      'clsType'         => $clsType,
                      'clsIcon'         => $clsIcon,
                      'msgBoxDisp'      => $msgBoxDisp);
        $this->msmarty->view($controlName . '/modules_group_addedit', $data);
	}
	/**
	 * @function  saveGroupModules
	 *
	 * @author    Vo Thanh Minh <thanhminhld@yahoo.com - thanhminhld@gmail.com>
	 * @access	  private
	 * @param
	 * @return
	 */
	private function saveGroupModules()
	{
        $controlName    = $this->input->get_post('c');

        $group_id       = $this->input->post('group_id');
        $data['g_name'] = $this->input->post('g_name');
        $m_id           = $this->input->post('m_name');

        if ( ! is_null($m_id) && count($m_id) > 0) {
            $data['m_id'] = implode(',', $m_id);
        }
        if (is_numeric($group_id) && $group_id > 0) {
            $fUpdate = true;
            $data['id'] = $group_id;
        } else {
            $fUpdate = false;
        }
		/**
		 * Load lang to show msg
		 */
		$this->lang->load('success', $this->lang_tag);
		$this->lang->load('error', $this->lang_tag);

		///// Start transaction /////
		/////////////////////////////
		$this->db->trans_begin();

		$ret = $this->module_group_model->storeTblWithoutLang($data, 'id', $fUpdate);

		if ($ret == FALSE) {
		    $this->messages->add($this->lang->line('db_insert_update_err'), 'error');
		    // Rollback transaction
		    $this->db->trans_rollback();
		} else {
            if ($fUpdate) {
                $this->messages->add($this->lang->line('db_update_success'), 'success');
            } else {
                $this->messages->add($this->lang->line('db_insert_success'), 'success');
            }
            // Commit transaction
            $this->db->trans_commit();
		}
		defaultPage($controlName);
	}
    /**
     * @function delGroupModules
     *
     * @author   Vo Thanh Minh <thanhminhld@yahoo.com - thanhminhld@gmail.com>
     * @access   private
     * @param
     * @return
     */
	private function delGroupModules()
	{
        $controlName = $this->input->get_post('c');
        $g_id        = $this->input->get_post('id');
		/**
		 * Load lang to show msg
		 */
		$this->lang->load('success', $this->lang_tag);
		$this->lang->load('error', $this->lang_tag);

        if (!is_numeric($g_id) || $g_id <= 0) {
            $this->messages->add($this->lang->line('value_stranfer_err'), 'error');
            defaultPage($controlName);
            return FALSE;
        }
        $arrWhere = array('id' => $g_id);
        $ret = $this->module_group_model->deleteTbl($arrWhere, 'id');
        if ($ret == true) {
            $this->messages->add($this->lang->line('db_delete_success'), 'success');
        } else {
            $this->messages->add($this->lang->line('db_insert_update_err'), 'error');
        }
        defaultPage($controlName);
	}
    /**
     * @function getErrMsg
     *
     * @author   Vo Thanh Minh <thanhminhld@yahoo.com - thanhminhld@gmail.com>
     * @access   private
     * @param    string $msgBoxDisp, $clsType, $clsIcon
     * @return   array
     */
    private function getErrMsg(&$msgBoxDisp, &$clsType, &$clsIcon)
    {
        $messages = $this->messages->get();

        if (!is_array($messages)) {
            $messages = array();
            $msgBoxDisp = 'none;';
        } else {
            foreach($messages as $type => $message) {
                if(!empty($message)) {
                    if ($type == 'error') {
                        $clsType = $type;
                        $clsIcon = 'errorIcon';
                    } else if ($type == 'success') {
                        $clsType = $type;
                        $clsIcon = 'successIcon';
                    }
                    break;
                }
            }
        }
        $this->messages->clear();
        return $messages;
    }
}
